package com.sy.simpleegg.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.sy.simpleegg.R
import com.sy.simpleegg.databinding.DialogCoinsInfoBinding
import com.sy.simpleegg.ext.countDown
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.ext.showToastMsg
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel


class CoinsInfoDialog(
    private val title: String?,
    private val msg: String?,
    private val needCoins: String,
    private val countDownTime: Int,
    private var listener: OutInfoDialogListener,
): DialogFragment() {

    private lateinit var binding: DialogCoinsInfoBinding

    private var isRunning = true

    private var timeDownScope: CoroutineScope? = null

    override fun onStart() {
        super.onStart()
//        dialog!!.window!!.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)

        val width = resources.getDimensionPixelSize(R.dimen.dialog_coins_info_width)
        val height = resources.getDimensionPixelSize(R.dimen.dialog_coins_info_height)
//        val marginBottom = resources.getDimensionPixelSize(R.dimen.dialog_good_detail_margin_bottom)

//        dialog!!.window!!.setLayout(width, height + marginBottom)
        dialog!!.window!!.setLayout(width, height)
        dialog!!.window!!.setGravity(Gravity.CENTER)
        dialog!!.setCanceledOnTouchOutside(false)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {
        binding = DialogCoinsInfoBinding.inflate(inflater, container, false)
//        setStyle(STYLE_NO_TITLE, R.style.MyDialog)
//        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT))
//        dialog!!.window!!.setGravity(Gravity.BOTTOM)
        dialog!!.window!!.setBackgroundDrawableResource(R.color.transparent)
//        var wlp = dialog!!.window!!.attributes
//        wlp.gravity = Gravity.BOTTOM
//        wlp.width = WindowManager.LayoutParams.MATCH_PARENT
//        wlp.height = WindowManager.LayoutParams.MATCH_PARENT
//        dialog!!.window!!.attributes = wlp

        return binding.root
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        try {
            binding.tvTitle.text = title
            binding.tvResult.text = msg
            binding.tvNeedCoin.text = needCoins
            binding.tvRemainCoin.text = needCoins
            binding.layoutClose.tvDismiss.text = "${countDownTime}S"

            binding.layoutClose.tvClose.setOnClickListener {
//                dismissAllowingStateLoss()
            }
            binding.btnBack.setOnClickListener {
                if (isRunning){
                    showToastMsg("工作中，请稍后")
                    return@setOnClickListener
                }
                listener.back()
                dismissAllowingStateLoss()
            }
            isRunning = true

        }catch (e: Exception){
            e.printStackTrace()
            logFile("初始化页面异常：${e.message}")
        }
    }

    override fun showNow(manager: FragmentManager, tag: String?) {
        super.showNow(manager, tag)
        startCountDown(countDownTime)
    }

    override fun show(manager: FragmentManager, tag: String?) {
        super.show(manager, tag)
        startCountDown(countDownTime)
    }

    override fun show(transaction: FragmentTransaction, tag: String?): Int {
        val result = super.show(transaction, tag)
        startCountDown(countDownTime)
        return result

    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        listener.dismiss()
    }

    /**
     * 刷新二维码
     * @param qrCode 二维码数据
     */
    fun refreshInfo(remainCoins: String, finish: Boolean, success: Boolean){
        try {
            if (finish){
                startCountDown(5)
                isRunning = false
                binding.tvResult.text = if (success) getString(R.string.out_coins_finish) else getString(R.string.out_coins_finish_err)
            }else{
                startCountDown(countDownTime)
            }
            binding.tvRemainCoin.text = remainCoins
        }catch (e: Exception){
            e.printStackTrace()
            logFile("刷新二维码异常：${e.message}")
        }
    }

    @SuppressLint("SetTextI18n")
    private fun startCountDown(timeout: Int){
        timeDownScope?.cancel()

        countDown(
            time = timeout,
            start = {
                timeDownScope = it
                logFile("开始倒计时")
            },
            end = {
                logFile("结束倒计时")
            },
            next = {
                binding.layoutClose.tvDismiss.text = "${it}S"
                if (it == 0){
                    if (isRunning){
                        isRunning = false
                    }
                    dismissAllowingStateLoss()
                }
            })
    }

    interface OutInfoDialogListener{
        fun dismiss()

        fun back()
    }

    fun dpToPx(context: Context, dp: Int): Int {
        val density = context.resources.displayMetrics.density
        return Math.round(dp * density)
    }
}